package cn.chiship.framework.common.config.filter;

import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.util.http.CustomRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决跨域  过滤器
 *
 * @author lijian
 */
@Component
public class CorsFilter implements Filter {

    private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json";
    private static final Logger LOGGER = LoggerFactory.getLogger(CorsFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type,Encrypt,ProjectsId,Access-Token,App-Key,App-Id,Sign,Application-Name");
        response.setHeader("Access-Control-Expose-Headers", "Content-disposition,Download-FileName");
        HttpServletRequest request = (HttpServletRequest) req;
        String contentType = request.getHeader("Content-Type");
        if (!StringUtil.isNullOrEmpty(contentType) && contentType.indexOf(CONTENT_TYPE_APPLICATION_JSON) > -1) {
            ServletRequest requestWrapper = new CustomRequestWrapper((HttpServletRequest) req);
            chain.doFilter(requestWrapper, response);
        } else {
            chain.doFilter(req, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}
